package com.okay.volume

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.RectF
import android.util.AttributeSet
import android.util.Log
import android.view.View
import androidx.core.content.ContextCompat
import com.okay.testclass.R
import com.okay.util.DensityUtils

/**
 * 麦克风检测时跳动的进度条
 */
class VolumeBarView(context: Context?, attrs: AttributeSet?) : View(context, attrs) {

    private var paint: Paint? = null
    private var minProgress: Float = 0f//默认最小值就是0%
    private var maxProgress: Float = 100f//最大值默认是100%
    private var progress: Float = minProgress
    private var rounded = DensityUtils.dp2px(context, 2f).toFloat()//圆角角度


    /**
     * 添加进度
     */
    fun setSize(progress: Float) {
        Log.d("test111", "progress:  $progress")
        if (progress > 100 || progress < 0) return

        if (progress >= minProgress) {//必须得大于最小值才可以赋值
            this.progress = progress
        } else {
            this.progress = minProgress
        }
        postInvalidate()
    }

    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)

        //初始化画笔
        paint = Paint(Paint.ANTI_ALIAS_FLAG)
        paint?.color = ContextCompat.getColor(context, R.color.color_E2E2E2)
        paint?.style = Paint.Style.FILL
        paint?.strokeWidth = 1f

        //外圈进度条长宽
        val width = width.toFloat()
        val height = height.toFloat()

        //绘制外圈圆角矩形
        canvas?.drawRoundRect(RectF(0f, 0f, width, height), rounded, rounded, paint!!)

        paint?.color = ContextCompat.getColor(context, R.color.color_007AFF)

        var ww: Float = width / maxProgress  //每1%占用的宽度

        //绘制内圈圆角矩形
        var rectf = RectF(0f, 0f, (ww * progress), height)
        canvas?.drawRoundRect(rectf, rounded, rounded, paint!!)
    }

}